package com.ljfiction.book.activitys;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.BookdatasBean;
import com.ljfiction.book.Baner.HotConmmentBean;
import com.ljfiction.book.Baner.MuchDashangBean;
import com.ljfiction.book.Dialog.LoadingDIalog;
import com.ljfiction.book.Dialog.ToSubcritDialog;
import com.ljfiction.book.Dialog.TotouweixiaomijinjiaoDialog;
import com.ljfiction.book.MyView.CircularImageView;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.MyView.NoScrollGridView;
import com.ljfiction.book.MyView.ObservableScrollView;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.ConmmentDatasAdapter;
import com.ljfiction.book.adapter.FensiAdapter_bookDatals;
import com.ljfiction.book.adapter.RecycleAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.AppUtils;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.ShareTool;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.sunfusheng.marqueeview.MarqueeView;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jaydenxiao.com.expandabletextview.ExpandableTextView;
import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import okhttp3.Call;
import okhttp3.Response;

public class BookDetailsActivity extends BaseActivity implements ObservableScrollView.ScrollViewListener {
    public static int isgridviewselect = 0;//选中的money
    @BindView(R.id.etv)
    ExpandableTextView etv;
    @BindView(R.id.clickmum_datals)
    TextView clickmumDatals;
    @BindView(R.id.reward_datals)
    TextView rewardDatals;
    @BindView(R.id.ticketmum_datals)
    TextView ticketmumDatals;
    @BindView(R.id.golden_datals)
    TextView goldenDatals;
    @BindView(R.id.muchchapter_bookdatals)
    TextView muchchapterBookdatals;
    @BindView(R.id.updata_bookdatals)
    TextView updataBookdatals;
    @BindView(R.id.writerimg_bookdatals)
    CircularImageView writerimgBookdatals;
    @BindView(R.id.writername_bookdatals)
    TextView writernameBookdatals;
    @BindView(R.id.fensigridview_datals)
    NoScrollGridView fensigridviewDatals;
    @BindView(R.id.muchfensi_bookdatals)
    LinearLayout muchfensiBookdatals;
    @BindView(R.id.id_recyclerview_horizontal)
    RecyclerView idRecyclerviewHorizontal;
    @BindView(R.id.bookimage_bookdatals)
    ImageView bookimageBookdatals;
    @BindView(R.id.back_bookdatals)
    ImageView backBookdatals;
    @BindView(R.id.scrollview_bookdatals)
    ObservableScrollView scrollviewBookdatals;
    @BindView(R.id.topbar_bookdatals)
    LinearLayout topbarBookdatals;
    @BindView(R.id.daohanglan)
    LinearLayout daohanglan;
    @BindView(R.id.fensinum)
    TextView fensinum;
    @BindView(R.id.bookName_bookdatas)
    TextView bookNameBookdatas;
    @BindView(R.id.condition_bookdatas)
    TextView conditionBookdatas;
    @BindView(R.id.bookNum_bookdatas)
    TextView bookNumBookdatas;
    @BindView(R.id.bookClassification_bookdatas)
    TextView bookClassificationBookdatas;
    @BindView(R.id.subcribimage_bookdatas)
    ImageView subcribimageBookdatas;
    @BindView(R.id.bookdetails_topback)
    ImageView bookdetailsTopback;
    @BindView(R.id.jiaguanzhu_datals)
    TextView jiaguanzhuDatals;
    @BindView(R.id.isAddbook)
    ImageView isAddbook;
    @BindView(R.id.recomenlistview_bookdatals)
    RecyclerView recomenlistviewBookdatals;
    @BindView(R.id.dashangnum)
    TextView dashangnum;
    @BindView(R.id.bootom_bookdatals)
    LinearLayout bootomBookdatals;
    @BindView(R.id.whodashangtext)
    MarqueeView whodashangtext;
    @BindView(R.id.username_bookdatas)
    TextView usernameBookdatas;
    @BindView(R.id.biaoqian_bookdatas)
    RecyclerView biaoqianBookdatas;
    @BindView(R.id.shear_bookdatals)
    ImageView shearBookdatals;
    @BindView(R.id.path)
    ImageView path;
    @BindView(R.id.zhengwen)
    ImageView zhengwen;
    @BindView(R.id.imageView_givereward)
    ImageView imageViewGivereward;
    @BindView(R.id.imageview_feed)
    ImageView imageviewFeed;
    @BindView(R.id.imageview_golden)
    ImageView imageviewGolden;
    @BindView(R.id.dashangtaxt)
    TextView dashangtaxt;
    @BindView(R.id.dashangqu)
    RelativeLayout dashangqu;
    @BindView(R.id.catalogue_datas)
    LinearLayout catalogueDatas;
    @BindView(R.id.moreComment_bookdatas)
    TextView moreCommentBookdatas;
    @BindView(R.id.tofensiliebiao)
    LinearLayout tofensiliebiao;
    @BindView(R.id.addbookshelf_bookdatals)
    LinearLayout addbookshelfBookdatals;
    @BindView(R.id.read_bookdatals)
    LinearLayout readBookdatals;
    @BindView(R.id.subscribe_bookdatals)
    LinearLayout subscribeBookdatals;
    private BookdatasBean bookdetails;
    private List<BookdatasBean.DataBean.FansInfoListBean.ListBean> listuser = new ArrayList<>();
    private List<BookdatasBean.DataBean.SimilarRecommendationBean> listBook = new ArrayList<>();
    private List<HotConmmentBean.DataBean> listComment = new ArrayList<>();
    private BookdatasBean.DataBean.BookListInfoBean book;
    private List<BookdatasBean.DataBean.BookLableBean> listBooklable = new ArrayList<>();
    private BookdatasBean.DataBean.BookdateBean bookdata;
    private BookdatasBean.DataBean.AuthorInfoBean authorInfoBean;
    private int imageHeight;
    private String bookid = "1";
    private FensiAdapter_bookDatals fensiAdapter;
    private ConmmentDatasAdapter conmmentDatasAdapter;
    private RecycleAdapter mAdapter;
    private boolean isZidong = false;
    private TotouweixiaomijinjiaoDialog totouweixiaomijinjiaoDialog;
    private HotConmmentBean bookCommentBean;
    private Context context;
    private ViewHolder viewHolder;
    private LoadingDIalog dIalog;
    private MuchDashangBean muchbean;
    private List<String> dashangdatas = new ArrayList<>();
    private BaseQuickAdapter biaoqianAdapter;
    private ToSubcritDialog toSubcritDialog;
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_details);
        ButterKnife.bind(this);
        context = this;
        bookid = getIntent().getStringExtra("bookId");
        AppUtils.init(this);
        intView();
        intData();
        toDashangDatas();
        initEvent();
        if (UserManageBean.isLogin()) {
            toZidong("search");
        }
        todaohanglanHeight(daohanglan, this);
        imageHeight = ScreenUtils.getNum(this, 70);
        scrollviewBookdatals.setScrollViewListener(BookDetailsActivity.this);//设置顶部滑动监听
        topbarBookdatals.getBackground().setAlpha(0);
    }

    private void toDashangDatas() {
        OkHttpUtils.post(HttpManager.IP + "/getSpicyirewardticketlogByBookId")

                .params("bookid", bookid)
                .execute(new StringCallback() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson g = new Gson();
                        try {
                            muchbean = g.fromJson(s, MuchDashangBean.class);
                            if (muchbean.getReturnCode() == 200) {
                                dashangdatas.clear();
                                dashangnum.setText("(" + String.valueOf(muchbean.getData().getTotal()) + ")");
                                for (MuchDashangBean.DataBean.ListBean i :
                                        muchbean.getData().getList()) {
                                    dashangdatas.add(i.getPseudonym() + "投喂了" + i.getSpicyiTicketCount() + "辣椒");
                                }
                                if (dashangdatas.size() > 0) {
                                    whodashangtext.startWithList(dashangdatas);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intView() {
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        idRecyclerviewHorizontal.setLayoutManager(linearLayoutManager);
        mAdapter = new RecycleAdapter(R.layout.recycelview_bookdatas, listBook);
        idRecyclerviewHorizontal.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(BookDetailsActivity.this, BookDetailsActivity.class);
            intent.putExtra("bookId", String.valueOf(listBook.get(position).getBookId()));
            startActivity(intent);
        });
        fensiAdapter = new FensiAdapter_bookDatals(listuser, this);
        fensigridviewDatals.setAdapter(fensiAdapter);
        fensigridviewDatals.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent1 = new Intent(BookDetailsActivity.this, UserCenterActivity.class);
            intent1.putExtra("userId", String.valueOf(listuser.get(position).getUserId()));
            startActivity(intent1);
        });
        muchfensiBookdatals.setOnClickListener(v -> {
            Intent intent4 = new Intent(BookDetailsActivity.this, FansRankActivity.class);
            intent4.putExtra("bookId", bookid);
            startActivity(intent4);
        });
        conmmentDatasAdapter = new ConmmentDatasAdapter(R.layout.comment_bookdatas, listComment);
        recomenlistviewBookdatals.setAdapter(conmmentDatasAdapter);
        recomenlistviewBookdatals.setLayoutManager(new LinearLayoutManager(this));
        recomenlistviewBookdatals.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        conmmentDatasAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Intent intent1 = new Intent(BookDetailsActivity.this, UserCenterActivity.class);
            intent1.putExtra("userId", String.valueOf(listComment.get(position).getUserId()));
            startActivity(intent1);
        });
        conmmentDatasAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent6 = new Intent(BookDetailsActivity.this, ShupingDatasActivity.class);
            intent6.putExtra("thisshuping", listComment.get(position));
            startActivityForResult(intent6, 8);
        });
        //设置布局管理器
        LinearLayoutManager linearLayou = new LinearLayoutManager(this);
        linearLayou.setOrientation(LinearLayoutManager.HORIZONTAL);
        biaoqianBookdatas.setLayoutManager(linearLayou);
        biaoqianBookdatas.setAdapter(biaoqianAdapter = new BaseQuickAdapter<BookdatasBean.DataBean.BookLableBean, BaseViewHolder>(R.layout.homhotnewrecycal, listBooklable) {
            @Override
            protected void convert(BaseViewHolder helper, BookdatasBean.DataBean.BookLableBean item) {
                AutoUtils.autoSize(helper.itemView);
                helper.setText(R.id.lablebordertext, item.getBookLableName()).setTextColor(R.id.lablebordertext, Color.parseColor(item.getBookColor()));
            }
        });

    }

    private void intData() {
        OkHttpUtils.post(HttpManager.IP + "/book-bookInfo")

                .params("bookid", bookid)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        dIalog = new LoadingDIalog(context);
                        dIalog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            Gson gson = new Gson();
                            bookdetails = gson.fromJson(s, BookdatasBean.class);
                            if (bookdetails.getReturnCode() == 200) {
                                scrollviewBookdatals.setVisibility(View.VISIBLE);
                                bootomBookdatals.setVisibility(View.VISIBLE);
                                dIalog.dismis();
                                loadData();
                            } else {
                                showToast(bookdetails.getMsg());
                                goBack();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            goBack();
                        }
                    }
                });
        OkHttpUtils.post(HttpManager.IP + "/comm-HotCommentInfo")

                .params("bookid", bookid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            bookCommentBean = gson.fromJson(s, HotConmmentBean.class);
                            if (200 == bookCommentBean.getReturnCode()) {
                                toPinglun();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toPinglundata() {
        OkHttpUtils.post(HttpManager.IP + "/comm-HotCommentInfo")

                .params("bookid", bookid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            bookCommentBean = gson.fromJson(s, HotConmmentBean.class);
                            if (200 == bookCommentBean.getReturnCode()) {
                                toPinglun();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toPinglun() {
        listComment.clear();
        if (bookCommentBean.getData().size() < 3) {
            listComment = bookCommentBean.getData();
        } else {
            listComment.add(bookCommentBean.getData().get(0));
            listComment.add(bookCommentBean.getData().get(1));
        }
        conmmentDatasAdapter.setNewData(listComment);

    }

    private void initEvent() {
        backBookdatals.setOnClickListener(v -> goBack());
    }


    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y,
                                int oldx, int oldy) {
        // Log.i("TAG", "y--->" + y + "    height-->" + height);
        if (y <= 0) {
            topbarBookdatals.getBackground().setAlpha(0);//AGB由相关工具获得，或者美工提供
        } else if (y <= imageHeight) {
            float scale = (float) y / imageHeight;
            int alpha = (int) (255 * scale);
            //只是layout背景透明(仿知乎滑动效果)
            topbarBookdatals.getBackground().setAlpha(alpha);
            remamberAlph = alpha;
        } else {
            topbarBookdatals.getBackground().setAlpha(255);
        }
    }

    @SuppressLint("SetTextI18n")
    private void loadData() {
        try {
            //书籍信息
            book = bookdetails.getData().getBookListInfo();
            book.setLastUpdateTime(bookdetails.getData().getLastChapterView().getReleaseTime());
            Glide.with(getApplicationContext()).load(book.getBookImage()).bitmapTransform(new BlurTransformation(this, 100)).into(bookdetailsTopback);
            if (book.getBookAuthorization() == 1 || book.getBookAuthorization() == 2) {
                path.setVisibility(View.VISIBLE);
            } else {
                path.setVisibility(View.GONE);
            }
            if (book.getCollectionDocuments() == 1) {
                path.setVisibility(View.GONE);
                zhengwen.setVisibility(View.VISIBLE);
            }
            //粉丝
            tofensiView();
            //是否加入书架
            toisAddbook();
            //同类书籍
            listBook.clear();
            listBook.addAll(bookdetails.getData().getSimilarRecommendation());
            mAdapter.notifyDataSetChanged();
            listBooklable.clear();
            for (int i = 0; i < (bookdetails.getData().getBookLable().size() > 4 ? 4 : bookdetails.getData().getBookLable().size()); i++) {
                listBooklable.add(bookdetails.getData().getBookLable().get(i));
            }
            biaoqianAdapter.notifyDataSetChanged();
            bookdata = bookdetails.getData().getBookdate();
            //总章数
            muchchapterBookdatals.setText("共" + bookdetails.getData().getChapterCount() + "章");
            toguanzhuView();
            //书的信息
            toBook();
            //作者的信息
            authorInfoBean = bookdetails.getData().getAuthorInfo();
            Glide.with(this).load(authorInfoBean.getUserHeadPortraitURL()).into(writerimgBookdatals);
            writernameBookdatals.setText(authorInfoBean.getPseudonym());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void toguanzhuView() {
        if (bookdetails.getData().getAuthorInfo().getIsfollow() == 1) {
            jiaguanzhuDatals.setText("已关注");
            jiaguanzhuDatals.setTextColor(Color.parseColor("#ffffff"));
            jiaguanzhuDatals.setBackgroundResource(R.drawable.shape_rediusred);
        } else {
            jiaguanzhuDatals.setText("+关注");
            jiaguanzhuDatals.setTextColor(Color.parseColor("#F77583"));
            jiaguanzhuDatals.setBackgroundResource(R.drawable.shape_radius);
        }
    }

    private void tofensiView() {
        listuser.removeAll(listuser);
        listuser.addAll(bookdetails.getData().getFansInfoList().getList());
        if (listuser.size() == 0) {
            fensigridviewDatals.setVisibility(View.GONE);
            fensinum.setText("暂无粉丝");
        } else {
            fensigridviewDatals.setVisibility(View.VISIBLE);
            fensiAdapter.notifyDataSetChanged();
            fensinum.setText(String.valueOf(bookdetails.getData().getFansInfoList().getTotal()));
        }
    }

    @SuppressLint("SetTextI18n")
    private void toBook() {
        bookNameBookdatas.setText(book.getBookName());//书名
        usernameBookdatas.setText(book.getWriterName());
        bookNumBookdatas.setText(StringTool.getNum(book.getBookWorldCount()) + "字");//书总字数
        bookClassificationBookdatas.setText(book.getClassificationName());//分类
        //书籍状态
        if (book.getBookStatus() == 1) {
            conditionBookdatas.setText("已完结");
            conditionBookdatas.setTextColor(Color.parseColor("#ff6f00"));
        }

        Glide.with(this).load(book.getBookImage()).bitmapTransform(new RoundedCornersTransformation(this, 10, 1)).into(bookimageBookdatals);//书封面

        etv.setText(book.getBookIntroduction());
        //书籍数据
        toChangeBookdatasnum();
        updataBookdatals.setText(TimeTool.getTimeAndChange(bookdetails.getData().getLastChapterView().getReleaseTime() + ""));

    }

    @SuppressLint("SetTextI18n")
    private void toChangeBookdatasnum() {
        clickmumDatals.setText("点击量" + StringTool.getClicknum(bookdata.getBookClickCount()));
        rewardDatals.setText(StringTool.getNum(bookdata.getAreward()) + "打赏");
        ticketmumDatals.setText(StringTool.getNum(bookdata.getBookRecommend()) + "小米椒");
        goldenDatals.setText(StringTool.getNum(bookdata.getGoldenTicket()) + "金椒");
    }

    @OnClick({R.id.imageView_givereward, R.id.imageview_feed, R.id.imageview_golden, R.id.catalogue_datas, R.id.writerimg_bookdatals, R.id.tofensiliebiao, R.id.addbookshelf_bookdatals, R.id.read_bookdatals, R.id.subscribe_bookdatals, R.id.bookdetails_topback, R.id.jiaguanzhu_datals, R.id.moreComment_bookdatas, R.id.dashangqu, R.id.shear_bookdatals})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.shear_bookdatals:
                if (book==null){
                    return;
                }

                ShareTool.toShare(BookDetailsActivity.this, book.getBookName(), String.valueOf(book.getBookId()), book.getBookImage(), book.getBookIntroduction(), String.valueOf(UserManageBean.userBean.getUserId()));
                break;
            case R.id.imageView_givereward:
                if (toSubcritDialog == null) {
                    toSubcritDialog = new ToSubcritDialog(BookDetailsActivity.this, bookid, bookdata.getBookName(), String.valueOf(authorInfoBean.getUserId()));
                    toSubcritDialog.setListener(new ToSubcritDialog.Listener() {
                        @Override
                        public void subclickok() {
                            toChangeBookData(1);
                            toDashangDatas();
                        }

                        @Override
                        public void subnologin() {
                            Intent intent = new Intent(BookDetailsActivity.this, LoginActivity.class);
                            startActivity(intent);
                        }
                    });
                } else {
                    toSubcritDialog.show();
                }

                break;
            case R.id.imageview_feed:
                toshowgiveDialog(0);
                break;
            case R.id.imageview_golden:
                toshowgiveDialog(1);
                break;
            case R.id.catalogue_datas:
                Intent intent2 = new Intent(BookDetailsActivity.this, ContentsActivity.class);
                intent2.putExtra("bookId", bookid);
                intent2.putExtra("bookName", bookdata.getBookName());
                startActivity(intent2);
                break;
            case R.id.writerimg_bookdatals:
                Intent intent1 = new Intent(BookDetailsActivity.this, UserCenterActivity.class);
                intent1.putExtra("userId", String.valueOf(book.getBookWriterId()));
                startActivity(intent1);
                break;
            case R.id.jiaguanzhu_datals:
                if (!UserManageBean.isLogin(this)) {
                    return;
                } else if (authorInfoBean.getIsfollow() == 1) {
                    return;
                } else if (authorInfoBean.getUserId() == UserManageBean.userBean.getUserId()) {
                    showToast("不能关注自己哦");
                    return;
                } else {
                    toguanzhu();
                }
                break;
            case R.id.tofensiliebiao:
                break;

            case R.id.addbookshelf_bookdatals:
                if (!UserManageBean.isLogin(this)) {
                    return;
                } else if (book.getCollectionStatus() == 1) {
                    return;

                } else {
                    toAddBook();
                }

                break;
            case R.id.read_bookdatals:
                Intent intent = new Intent(this, Reading2Activity.class);
                intent.putExtra("bookId", bookid);
                startActivity(intent);
                break;
            case R.id.subscribe_bookdatals:
                if (isZidong) {
                    return;
                } else {
                    if (popupWindow != null && !popupWindow.isShowing()) {
                        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                    } else {
                        showPopuWindow(view);
                    }
                }
                break;
            case R.id.bookdetails_topback:

                break;
            case R.id.moreComment_bookdatas:
                Intent intent3 = new Intent(this, AuthShuPingActivity.class);
                intent3.putExtra("bookId", bookid);
                intent3.putExtra("bookName", book.getBookName());
                startActivityForResult(intent3, 8);
                break;
            case R.id.dashangqu:
                Intent intent5 = new Intent(BookDetailsActivity.this, DashangbookdatasActivity.class);
                intent5.putExtra("bookId", bookid);
                startActivity(intent5);
                break;
        }
    }

    //i=0弹出给小米椒的dialog，1是弹出给金椒的dialog
    private void toshowgiveDialog(int i) {
        if (totouweixiaomijinjiaoDialog == null) {
            totouweixiaomijinjiaoDialog = new TotouweixiaomijinjiaoDialog(BookDetailsActivity.this, bookid, bookdata.getBookName(), String.valueOf(authorInfoBean.getUserId()));
            totouweixiaomijinjiaoDialog.setListener(new TotouweixiaomijinjiaoDialog.Listener() {
                @Override
                public void subclickok() {
                    toChangeBookData(1);
                }

                @Override
                public void clickquhao() {
                    Intent intent = new Intent(BookDetailsActivity.this, SelectquhaoActivity.class);
                    startActivityForResult(intent, 10);
                }

                @Override
                public void subnologin() {
                    Intent intent = new Intent(BookDetailsActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
        }
        totouweixiaomijinjiaoDialog.show(i);

    }

    private void toAddBook() {
        OkHttpUtils.post(HttpManager.IP + "/bookshelf-adduserbookshelf")

                .params("userName", UserManageBean.userBean.getPseudonym())
                .params("bookId", bookid)
                .params("bookName", book.getBookName())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                book.setCollectionStatus(1);
                                isAddbook.setImageResource(R.drawable.addbookletok);
                            } else if (js.getInt("returnCode") == 400) {
                                Intent intent = new Intent(BookDetailsActivity.this, LoginActivity.class);
                                startActivity(intent);
                            }
                            showToast(js.getString("msg"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toguanzhu() {
        OkHttpUtils.post(HttpManager.IP + "/fans-addFans")

                .params("followId", String.valueOf(authorInfoBean.getUserId()))
                .params("followUserName", authorInfoBean.getPseudonym()).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.getInt("returnCode") == 200) {
                        toChangeBookData(2);
                    } else if (400 == jsonObject.getInt("returnCode")) {
                        Intent intent = new Intent(BookDetailsActivity.this, LoginActivity.class);
                        startActivity(intent);
                        showToast(jsonObject.getString("msg"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        });
    }

    private void showPopuWindow(View view) {
        View contentView = null;

        contentView = LayoutInflater.from(this).inflate(R.layout.subscription_bookdata, null);
        popupWindow = new PopupWindow(contentView);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isZidong) {
                    toZidong("update");
                    subcribimageBookdatas.setImageResource(R.drawable.subscribeok);
                } else {
                    subcribimageBookdatas.setImageResource(R.drawable.subscribe);
                }
                backGroudback();
            }
        });
        viewHolder = new ViewHolder(contentView);
        viewHolder.residual.setText(String.valueOf(UserManageBean.userBean.getUserMoney()));
        viewHolder.selectZidong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserManageBean.isLogin(BookDetailsActivity.this)) {
                    popupWindow.dismiss();
                    return;
                }
                if (isZidong) {
                    isZidong = false;
                    viewHolder.selectZidong.setImageResource(R.drawable.normasel);
                } else {
                    isZidong = true;
                    viewHolder.selectZidong.setImageResource(R.drawable.selectzidong);
                }
            }
        });
        viewHolder.superButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BookDetailsActivity.this, PursActivity.class);
                startActivity(intent);
            }
        });
        //使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);
        //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources()));
        //产生背景变暗效果
        tobackgroud();
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(ScreenUtils.getScreenWidth());
        popupWindow.setHeight(ScreenUtils.getScreenHeight() / 5);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void backGroudback() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f;
        getWindow().setAttributes(lp);
    }

    private void tobackgroud() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);

    }

    private void toZidong(String type) {
        OkHttpUtils.post(HttpManager.IP + "/userRmemberChose")

                .params("bookid", bookid)
                .params("isSelect", "1")
                .params("type", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (200 == js.getInt("returnCode")) {
                                if (isZidong = js.getJSONObject("data").getInt("isClose") == 0 ? false : true) {
                                    subcribimageBookdatas.setImageResource(R.drawable.subscribeok);
                                } else {
                                    subcribimageBookdatas.setImageResource(R.drawable.subscribe);
                                }
                            } else {
                                subcribimageBookdatas.setImageResource(R.drawable.subscribe);
                                isZidong = false;
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toChangeBookData(final int type) {
        OkHttpUtils.post(HttpManager.IP + "/book-bookInfo")

                .params("bookid", bookid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            bookdetails = gson.fromJson(s, BookdatasBean.class);
                            if (bookdetails.getReturnCode() == 200) {
                                switch (type) {
                                    case 1:
                                        bookdata = bookdetails.getData().getBookdate();
                                        toChangeBookdatasnum();
                                        tofensiView();
                                        break;
                                    case 2:
                                        book = bookdetails.getData().getBookListInfo();
                                        toisAddbook();
                                        toguanzhuView();
                                        break;
                                }
                            } else {
                                showToast(bookdetails.getMsg());
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toisAddbook() {
        if (book.getCollectionStatus() == 1) {
            isAddbook.setImageResource(R.drawable.addbookletok);
        } else {
            isAddbook.setImageResource(R.drawable.addbooklet);
        }
    }

    /*
     *requestCode == 8从评论过来，刷新评
     * requestCode==10&&resultCode==10绑定手机号选择区号回来
     * */
    private int remamberAlph = 0;

    @Override
    protected void onResume() {
        super.onResume();
        topbarBookdatals.getBackground().setAlpha(remamberAlph);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 8) {
            toPinglundata();
        } else if (requestCode == 10 && resultCode == 10) {
            if (totouweixiaomijinjiaoDialog != null) {
                totouweixiaomijinjiaoDialog.setQuhao(data.getStringExtra("countryNumber"));
            }
        }
    }

    @Override
    protected void onRestart() {
        toChangeBookData(2);
        toZidong("search");
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        SettingManager.finishInstance();
        System.gc();
        System.runFinalization();
        System.gc();
    }

    class ViewHolder {
        @BindView(R.id.residual)
        TextView residual;
        @BindView(R.id.select_zidong)
        ImageView selectZidong;
        @BindView(R.id.nowrecharge_give)
        SuperButton superButton;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
